﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThresholdAssistant.DataContract.Result;
using ThresholdAssistant.NLogSdk;
using ThresholdAssistant.Tools.Extensions;
using ThresholdAssistant.WebAPI.Models;
using ThresholdAssistant.WebAPI.Models.Constants;
using ThresholdAssistant.WebAPI.Repository;

namespace ThresholdAssistant.WebAPI.Service.JobService
{
    /// <summary>
    /// 读取文件并发送短信服务
    /// </summary>
    public class ReadFileToSendSmsService : BaseService
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        public MemberRepository MemberRepository { get; set; }
        /// <summary>
        /// 短信服务
        /// </summary>
        public HuyiSmsService HuyiSmsService { get; set; }

        /// <summary>
        /// 短信提醒定时器
        /// </summary>
        /// <returns></returns>
        public async Task ExecuteAsync()
        {
            //获取群主列表
            var list = await MemberRepository.GetMemberMasterList();
            if (list == null || list.Any() == false)
            {
                NLogUtil.Debug("没有群主信息，无法发送短信提醒");
                return;
            }
            //读取文件
            var lstSms = new List<SmsInfoParam>();
            SmsInfoParam model = null;
            list.ForEach(x =>
            {
                model = ThresholdFileService.ReadSms(x.GroupId.ToString(), AppSettingConstant.ThresholdServicePath);
                if (model != null)
                {
                    lstSms.Add(model);
                }
            });
            if (lstSms.Any() == false)
            {
                NLogUtil.Debug("没有短信需要发送");
                return;
            }

            NLogUtil.Trace($"发现有短信需要发送,共{lstSms.Count()}条，内容是：{JsonConvert.SerializeObject(lstSms)}");
            //发送短信
            var sendResult = new ContractResult();

            //大于500条分页处理，每页500条
            var pageIndex = 0;
            var pageSize = 500;
            var _smsList = new List<SmsInfoParam>();
            //var pageCount = Math.Ceiling(lstSms.Count() / pageSize * 1.0);
            var pageCount = lstSms.Count() %  pageSize > 0 ? (lstSms.Count() / pageSize) + 1 : (lstSms.Count() / pageSize);
            while (pageIndex < pageCount)
            {
                _smsList = lstSms.Skip(pageIndex * pageSize).Take(pageSize).ToList();
                if (_smsList?.Count() == 1)
                {
                    sendResult = await HuyiSmsService.SendSmsAsync(lstSms.First());
                }
                else
                {
                    sendResult = await HuyiSmsService.SendBatchSmsAsync(_smsList);
                }
                pageIndex++;
            }

            if (sendResult.Success == false)
            {
                return;
            }

            //删除短信
            lstSms.ForEach(x =>
            {
                ThresholdFileService.RemoveSms(x.GroupId.ToString(), AppSettingConstant.ThresholdServicePath);
            });
        }
    }
}
